from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from movies.models import Movie, Genre, Rating
import random

class Command(BaseCommand):
    help = '添加示例电影数据到数据库'

    def handle(self, *args, **kwargs):
        # 创建管理员账号
        if not User.objects.filter(username='admin').exists():
            User.objects.create_superuser('admin', 'admin@example.com', 'admin')
            self.stdout.write(self.style.SUCCESS('创建了管理员账号: admin / admin'))
        
        # 创建测试用户
        test_users = []
        for i in range(1, 6):
            username = f'user{i}'
            if not User.objects.filter(username=username).exists():
                user = User.objects.create_user(
                    username=username,
                    email=f'{username}@example.com',
                    password=username
                )
                test_users.append(user)
                self.stdout.write(self.style.SUCCESS(f'创建了测试用户: {username} / {username}'))
        
        # 创建电影类型
        genres = [
            '动作', '冒险', '喜剧', '犯罪', '剧情', '奇幻',
            '恐怖', '爱情', '科幻', '惊悚', '战争', '动画'
        ]
        
        genre_objects = []
        for genre_name in genres:
            genre, created = Genre.objects.get_or_create(name=genre_name)
            genre_objects.append(genre)
            if created:
                self.stdout.write(self.style.SUCCESS(f'创建了电影类型: {genre_name}'))
        
        # 示例电影数据
        sample_movies = [
            {
                'title': '肖申克的救赎',
                'year': 1994,
                'description': '两个被囚禁在肖申克监狱的男人多年来找到慰藉和最终的救赎通过共同的解脱行为。',
                'genres': ['剧情', '犯罪'],
                'poster_url': 'https://img2.doubanio.com/view/photo/l/public/p2372307693.webp'
            },
            {
                'title': '教父',
                'year': 1972,
                'description': '有组织犯罪家族的老大几乎退休，他最小的儿子不情愿地接手家族事业。',
                'genres': ['剧情', '犯罪'],
                'poster_url': 'https://img2.doubanio.com/view/photo/l/public/p2190556185.webp'
            },
            {
                'title': '阿甘正传',
                'year': 1994,
                'description': '阿拉巴马人福瑞斯特·甘，智商只有75，却过着不平凡的人生。',
                'genres': ['剧情', '爱情'],
                'poster_url': 'https://img2.doubanio.com/view/photo/l/public/p2372307693.webp'
            },
            {
                'title': '泰坦尼克号',
                'year': 1997,
                'description': '处于不同社会阶层的杰克和露丝在泰坦尼克号首航期间坠入爱河。',
                'genres': ['剧情', '爱情'],
                'poster_url': 'https://img9.doubanio.com/view/photo/l/public/p457760035.webp'
            },
            {
                'title': '星球大战：帝国反击战',
                'year': 1980,
                'description': '卢克·天行者和他的朋友在黑武士达斯·维达的追捕下展开刺激冒险。',
                'genres': ['科幻', '冒险'],
                'poster_url': 'https://img2.doubanio.com/view/photo/l/public/p2263141907.webp'
            },
            {
                'title': '指环王：王者归来',
                'year': 2003,
                'description': '甘道夫和亚拉冈带领刚铎的军队前往黑门，吸引索伦的军队远离魔戒持有者弗罗多。',
                'genres': ['奇幻', '冒险'],
                'poster_url': 'https://img2.doubanio.com/view/photo/l/public/p2442942825.webp'
            },
            {
                'title': '黑客帝国',
                'year': 1999,
                'description': '一名电脑黑客了解到他所知道的现实是一个由能够思考的机器创造的虚拟现实。',
                'genres': ['科幻', '动作'],
                'poster_url': 'https://img2.doubanio.com/view/photo/l/public/p451926968.webp'
            },
            {
                'title': '千与千寻',
                'year': 2001,
                'description': '小女孩千寻在一个奇异的小镇上冒险，父母变成了猪。',
                'genres': ['动画', '奇幻'],
                'poster_url': 'https://img1.doubanio.com/view/photo/l/public/p2557573348.webp'
            },
            {
                'title': '盗梦空间',
                'year': 2010,
                'description': '一个窃贼可以进入他人的梦境，被聘请进行心理植入，他必须挫败会破坏任务的敌人。',
                'genres': ['科幻', '冒险'],
                'poster_url': 'https://img9.doubanio.com/view/photo/l/public/p513344864.webp'
            },
            {
                'title': '霸王别姬',
                'year': 1993,
                'description': '京剧演员在动荡的中国历史变化中挣扎求生，尤其是在文化大革命期间。',
                'genres': ['剧情', '爱情'],
                'poster_url': 'https://img1.doubanio.com/view/photo/l/public/p2561716440.webp'
            },
        ]
        
        created_movies = []
        for movie_data in sample_movies:
            # 检查电影是否已存在
            if not Movie.objects.filter(title=movie_data['title'], year=movie_data['year']).exists():
                movie = Movie.objects.create(
                    title=movie_data['title'],
                    year=movie_data['year'],
                    description=movie_data['description'],
                    poster_url=movie_data['poster_url']
                )
                
                # 添加类型
                for genre_name in movie_data['genres']:
                    genre = Genre.objects.get(name=genre_name)
                    movie.genres.add(genre)
                
                created_movies.append(movie)
                self.stdout.write(self.style.SUCCESS(f'添加了电影: {movie_data["title"]}'))
        
        # 添加随机评分
        if test_users and created_movies:
            for user in test_users:
                # 每个用户评价3-7部电影
                num_ratings = random.randint(3, 7)
                movies_to_rate = random.sample(list(created_movies), min(num_ratings, len(created_movies)))
                
                for movie in movies_to_rate:
                    rating_value = random.randint(1, 5)
                    comment = f"这是{user.username}对《{movie.title}》的评价。"
                    
                    Rating.objects.create(
                        user=user,
                        movie=movie,
                        rating=rating_value,
                        comment=comment
                    )
                    self.stdout.write(self.style.SUCCESS(
                        f'用户 {user.username} 给 {movie.title} 评分 {rating_value}'
                    ))
        
        self.stdout.write(self.style.SUCCESS('成功添加示例数据!')) 